package beerAgent;

import evolutionaryProblems.Phenotype;
import fitnessFunctions.FitnessFunction;
import genotype.BeerGenotype;
import genotype.Genotype;

public class BeerPhenotype extends Phenotype {

	BeerGenotype genotype;
	FitnessFunction fitnessFunction;
	private int currentFitnessFunction;

	public BeerPhenotype(BeerGenotype genotype) {
		this.genotype = genotype;
		this.fitnessFunction = genotype.getParameters().getFitnessFunction();
		calculateFitness();
	}

	@Override
	public double getFitness() {
		if (!this.isEditable()) {
			return fitness;
		}
		BeerFitnessFunction ff = (BeerFitnessFunction) fitnessFunction;
		if (ff.getCurrentFitnessFunction() != this.currentFitnessFunction) {
			currentFitnessFunction = ff.getCurrentFitnessFunction(); 
			this.fitness = fitnessFunction.calculateFitness(this);
		}
		return fitness;
	}

	@Override
	public void calculateFitness() {
		currentFitnessFunction = ((BeerFitnessFunction) fitnessFunction)
				.getCurrentFitnessFunction();
		this.fitness = fitnessFunction.calculateFitness(this);
	}

	@Override
	public Genotype getGenotype() {
		return this.genotype;
	}

	@Override
	public boolean isSolution() {
		return this.fitness == 1.0 && currentFitnessFunction == 3;
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof BeerPhenotype) {
			BeerPhenotype other = (BeerPhenotype) o;
			return other.fitness == this.fitness
					&& other.currentFitnessFunction == this.currentFitnessFunction;
		}
		return false;
	}

	@Override
	public String toString() {
		String theString = super.toString();
		theString += " T:" + currentFitnessFunction;
		return theString;
	}

	public int getCurrentFitnessFunction() {
		return currentFitnessFunction;
	}

	public void externalPhenotypeSetup(int testGames) {
		this.currentFitnessFunction = testGames;
		calculateFitness();
		setEditable(false);
		setGeneration(-2);
	}
	
	public Phenotype getListClone(int generation){
		if (generation != -2) {
			BeerPhenotype clone = (BeerPhenotype) super.getListClone(generation);
			clone.fitness = this.fitness; 
			return clone; 
		}else {
			BeerPhenotype clone = (BeerPhenotype) getGenotype().clone().evolveGenotype(); 
			clone.editable = false; 
			clone.generation = -2;
			clone.currentFitnessFunction = 3; 
			clone.calculateFitness(); 
			return clone; 
		}
	}

}
